 /**
* enterGroupChart functions
* copyright@Catosoft.com reserved, 2016
* 2016.06.20, created by Eric.Wang
*/



/*
* get data
*/
var getEnterGroupColumnData = function(){
	var data = {

	};
	var option = {
		url: '/draft/group/in/v1',
		type: 'GET',
		data: data,
	};
	createAjax(option, function(err, res){
		if(!err){
			enterGroupColumnChart('enterGroupColumnChart', res);
			enterGroupTable('enterGroupTable', res);
		}
	});
}

var getEnterGroupPieData = function(){
	var data = {

	};
	var option = {
		url: '/draft/group/rate/v1',
		type: 'GET',
		data: data,
	};
	createAjax(option, function(err, res){
		if(!err){
			enterGroupPieChart('enterGroupPieChart', res);
		}
	});
}

var getEnterGroupLineData = function(){
	var data = {

	};
	var option = {
		url: '/draft/group/stat/v1',
		type: 'GET',
		data: data,
	};
	createAjax(option, function(err, res){
		if(!err){
			enterGroupStatsLineChart('enterGroupStatsLineChart', res);
			enterGroupStatsColumnChart('enterGroupStatsColumnChart', res);
		}
	});
}

/*
* data filter
*/
var enterGroupColumnFilter = function(data){
	var series = [];
	$.each(data, function(index, item){
		var list = [];
		$.each(item.data, function(index, each){
			list.push([new Date((each.name + '-01').replace(/-/g,"/")).getTime(), each.num]);
		});
		series.push({
			name: item.name,
			data: list,
		});
	});
	return series;
}

var enterGroupStatsFilter = function(data){
	var categories = [];
	var series = [{
		name: '入组人数',
		data: []
	}];

	var monthMapByYear = {};
	var years = [];
	var seriesData = [];
	var prevYear = -1;
	var prevMonth = 0;
	data.forEach(function (item) {
		var pair = item.name.split('-');
		var year = +pair[0];
		var month = +pair[1];
		var label = year + '年' + month + '月';
		
		if (years.indexOf(year) === -1) {
			years.push(year);
			monthMapByYear[year] = [];

			if (prevYear !== -1) {
				for (var i = prevMonth; i < 12; i++) {
					var supplyLabel = prevYear + '年' + (i + 1) + '月';
					monthMapByYear[prevYear].push(supplyLabel);
					categories.push(supplyLabel);
					seriesData.push(seriesData[seriesData.length - 1]);
				}
			}

			prevYear = year;
			prevMonth = 0;
		}

		for (var i = prevMonth; i < month - 1; i++) {
			var supplyLabel = year + '年' + (i + 1) + '月';
			monthMapByYear[year].push(supplyLabel);
			categories.push(supplyLabel);
			seriesData.push(item.num);
		}

		monthMapByYear[year].push(label);
		categories.push(label);
		seriesData.push(item.num);

		prevMonth = month;
	});

	return {
		categories: categories,
		series: [{
			name: '入组人数',
			data: seriesData
		}],
		years: years,
		monthMapByYear: monthMapByYear
	};
}

var enterGroupTableFilter = function(data){
	var column = [];
	column.push({
		field: 'Number',  
    title: '序号',  
    formatter: function (value, row, index) {  
    	return index + 1;  
    },
    footerFormatter: function () {
    	return '总计';
    }
	});
	column.push({
		title: '中心',
		field: 'name',
		align: 'left',
	});
	$.each(data.list, function(index, item){
		var sum = 0;
		$.each(item.data, function(index, data){
			var key = data.name;
			item[key] = data.num;
			sum += data.num;
			if(index == 0){
				column.push({
					title: key,
					field: key,
					align: 'left',
					footerFormatter: sumFormatter
				});
			}
		});
		item['sum'] = sum;
	});
	column.push({
		title: '总计',
		field: 'sum',
		align: 'left',
		footerFormatter: sumFormatter
	});
	return column;
}

/*
* draw charts
*/
var enterGroupColumnChart = function(element, data){
	var series = enterGroupColumnFilter(data.list);
	var enterGroupColumnChartOption = {
		chart: {
	        type: 'column',
	        renderTo: element,
	        zoomType: 'x'
	    },
	    colors: colors[0],
		title: {
	        text: chartTitles.enterGroupColumn
	    },
	    xAxis: {
	    	title: {
	    		text: '时间'
	    	},
	    	type: 'datetime',
	    	labels: { 
				formatter: function() { 
	            	return Highcharts.dateFormat('%Y年%m月', this.value); 
				}
			}
	    },
	    yAxis: {
	        title: {
	            text: '入组人数'
	        },
	        plotLines: [{
	            value: 0,
	            width: 1,
	            color: '#808080'
	        }]
	    },
	    legend: {
	        layout: 'vertical',
	        align: 'right',
	        verticalAlign: 'middle',
	        borderWidth: 0
	    },
	    tooltip: {
	        xDateFormat: '%Y年%m月'
	    },
	    series: series,
	    credits: credits,
	    exporting: {
	    	buttons: {
	    		contextButton: {
	    			menuItems: getMenuItems(),
	    		}
	    	}
	    },
	};
	var chart = new Highcharts.Chart(enterGroupColumnChartOption);
}

var enterGroupPieChart = function(element, data){
	var enterGroupPieChartOption = {
		chart: {
	        renderTo: element,
	        plotShadow: true
	    },
	    colors: colors[0],
		title: {
	        text: chartTitles.enterGroupPie,
	    },
	    plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                }
            }
        },
	    legend: {
	        layout: 'vertical',
	        align: 'right',
	        verticalAlign: 'middle',
	        borderWidth: 0
	    },
	    series: [{
	    	type: 'pie',
	    	name: '人数',
	    	data: [
	    		['已入组人数', data.already],
	    		['应入组人数', data.should],
	    	]
	    }],
	    credits: credits,
	    exporting: {
	    	buttons: {
	    		contextButton: {
	    			menuItems: getMenuItems(),
	    		}
	    	}
	    }
	};
	var chart = new Highcharts.Chart(enterGroupPieChartOption);
}

var enterGroupStatsLineChart = function(element, data){
	var filter = enterGroupStatsFilter(data.list);
	var enterGroupStatsLineChartOption = {
		chart: {
	        renderTo: element,
	        zoomType: 'x',
	    },
	    colors: colors[0],
		title: {
	        text: chartTitles.enterGroupStatsLine,
	    },
	    xAxis: {
	    	title: {
	    		text: '时间',
	    	},
	    	categories: filter.categories
	    },
	    yAxis: {
	        title: {
	            text: '入组人数',
	        },
	        plotLines: [{
	            value: 0,
	            width: 1,
	            color: '#808080'
	        }]
	    },
	    legend: {
	        layout: 'vertical',
	        align: 'right',
	        verticalAlign: 'middle',
	        borderWidth: 0
	    },
	    tooltip: {
	        xDateFormat: '%Y年%m月',
	    },
	    series: filter.series,
	    credits: credits,
	    exporting: {
	    	buttons: {
	    		contextButton: {
	    			menuItems: getMenuItems(),
	    		}
	    	}
	    },
	};	
	var chart = new Highcharts.Chart(enterGroupStatsLineChartOption);

	$('#' + element).prepend(createSelectBoxByCategories(filter.years));

	seriesData = [];
	filter.series.forEach(function (serie, index) {
		seriesData[index] = [];
		serie.data.forEach(function (value) {
			seriesData[index].push(value);
		});
	});
	$('#' + element + ' .select-column-chart').on('change', (function (categoriesMap, chart, seriesData) {
		return function () {
			var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
			var index = +target.value;
			var year = $(event.currentTarget).find('option:selected').text();

			if (index === -1) {
				var yData = [];
				seriesData.forEach(function (data, i) {
					// yData.push({y: });
					/* yData = data.map(function (value) {
						return {y: value};
					});*/
					data.forEach(function (value) {
						yData.push({ y: value });
					});
				});

				var categories = [];
				for (var key in categoriesMap) {
					// Array.prototype.push.apply(categories, categoriesMap[key]);

					categoriesMap[key].forEach(function (category) {
						categories.push(category);
					});
				}
				chart.series[0].setData(yData);
				chart.xAxis[0].setCategories(categories);
			} else {
				seriesData.forEach(function (data, i) {
					var yData = [];
					for (var k = index * 12; k < index * 12 + Math.min(categoriesMap[year].length, 12); k++) {
						yData.push({y: data[k]});
					}
					chart.series[i].setData(yData);
				});
				chart.xAxis[0].setCategories(categoriesMap[year]);
			}
		}
	})(filter.monthMapByYear, chart, seriesData));
}

var enterGroupStatsColumnChart = function(element, data){
	var filter = enterGroupStatsFilter(data.list);
	var enterGroupStatsColumnChartOption = {
		chart: {
	        renderTo: element,
	        zoomType: 'x',
	        type: 'column',
	    },
	    colors: colors[0],
		title: {
	        text: chartTitles.enterGroupStatsColumn,
	    },
	    xAxis: {
	    	type: 'datetime',
	    	categories: filter.categories
	    },
	    yAxis: {
	        title: {
	            text: '入组人数',
	        },
	        plotLines: [{
	            value: 0,
	            width: 1,
	            color: '#808080'
	        }]
	    },
	    legend: {
	        layout: 'vertical',
	        align: 'right',
	        verticalAlign: 'middle',
	        borderWidth: 0
	    },
	    tooltip: {
	        xDateFormat: '%Y年%m月',
	    },
	    series: filter.series,
	    credits: credits,
	    exporting: {
	    	buttons: {
	    		contextButton: {
	    			menuItems: getMenuItems(),
	    		}
	    	}
	    },
	};
	var chart = new Highcharts.Chart(enterGroupStatsColumnChartOption);
	$('#' + element).prepend(createSelectBoxByCategories(filter.years));

	seriesData = [];
	filter.series.forEach(function (serie, index) {
		seriesData[index] = [];
		serie.data.forEach(function (value) {
			seriesData[index].push(value);
		});
	});
	$('#' + element + ' .select-column-chart').on('change', (function (categoriesMap, chart, seriesData) {
		return function () {
			var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
			var index = +target.value;
			var year = $(event.currentTarget).find('option:selected').text();

			if (index === -1) {
				var yData = [];
				seriesData.forEach(function (data, i) {
					// yData.push({y: });
					/* yData = data.map(function (value) {
						return {y: value};
					});*/
					data.forEach(function (value) {
						yData.push({ y: value });
					});
				});

				var categories = [];
				for (var key in categoriesMap) {
					// Array.prototype.push.apply(categories, categoriesMap[key]);

					categoriesMap[key].forEach(function (category) {
						categories.push(category);
					});
				}
				chart.series[0].setData(yData);
				chart.xAxis[0].setCategories(categories);
			} else {
				seriesData.forEach(function (data, i) {
					var yData = [];
					for (var k = index * 12; k < index * 12 + Math.min(categoriesMap[year].length, 12); k++) {
						yData.push({y: data[k]});
					}
					chart.series[i].setData(yData);
				});
				chart.xAxis[0].setCategories(categoriesMap[year]);
			}
		}
	})(filter.monthMapByYear, chart, seriesData));
}

var enterGroupTable = function(element, data){
	var column = enterGroupTableFilter(data);
	$('#' + element).bootstrapTable({
		data: data.list,
		classes: 'table table-hover',
		pagination: false,
		pageSize: 20,
		pageNumber: 1,
		pageList: [20, 50],
		sidePagination: 'client',
		showRefresh: true,
		showColumns: true,
		buttonsAlign: 'right',
		showExport: true,
		exportDataType: 'all',
		exportTypes: ['csv', 'txt', 'excel'],
		locale: 'zh-CN',
		columns: column,
		showFooter: true
	});
}

$(function(){
	getEnterGroupColumnData();
	getEnterGroupPieData();
	getEnterGroupLineData();
});